import "./utils/extend";
import cors from "cors";
import bodyParser from "body-parser";
import jwt from "express-jwt";
import { jwtSecret } from "./config";

// https://www.npmjs.com/package/cors

export function setupExpress(app, path0) {
  app.use(cors());
  app.use(
    bodyParser.json({
      limit: "5mb",
    })
  );
  app.use(
    bodyParser.urlencoded({
      extended: true,
      limit: "5mb",
    })
  );

  app.use(
    jwt({
      secret: jwtSecret,
      credentialsRequired: false,
      getToken(req) {
        req._jwtoken = req.headers.token || req.query._jwtoken;
        return req._jwtoken;
      },
    })
  );

  app.use((req, res, next) => {
    req.path0 = path0;
    req._body = { ...req.query, ...req.body };
    req.realIp = req.get("x-forwarded-for") || req.ip;
    const { host } = req.headers;
    req.origin = (/:/.test(host) ? "http" : "https") + "://" + host;

    next();
  });

  app.use(async (req, res, next) => {
    // console.log(req.path)
    const mock_uid = req.query["mock_uid_" + jwtSecret.substr(0, 3)];
    if (mock_uid) {
      req.user = {
        id: mock_uid,
        iat: (Date.now() / 1e3) | 0,
      };
    }
    // console.log(req.user)
    if (/\/auth\b/.test(req.path)) {
      if (!req.user)
        throw {
          msg: "Auth fail",
          code: 401,
        };
    }
    next();
  });
}
